package pl.edu.utp.kursy.database.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public abstract class BaseDao<T> implements Dao<T>{
    
    private enum BaseDaoOperation{CREATE, UPDATE, DELETE};
    
    protected SessionFactory sessionFactory;
    
    public BaseDao(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void create(T object) {
        execute(object, BaseDaoOperation.CREATE);
    }

    @Override
    public void update(T object) {
        execute(object, BaseDaoOperation.UPDATE);
    }

    @Override
    public void delete(T object) {
        execute(object, BaseDaoOperation.DELETE);
    }
    
    private void execute(T object, BaseDaoOperation operation){
        Session session = null;
        Transaction tx=null;
        try {
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            switch(operation){
                case CREATE:
                    session.save(object);
                    break;
                case UPDATE:
                    session.update(object);
                    break;
                case DELETE:
                    session.delete(object);
                    break;
            }
            
            session.flush();
            tx.commit();
        } catch (Exception ex) {
            if(tx != null){
                tx.rollback();
            }
        } finally{
            if(session != null) {
                session.close();
            }
        }
    }

    @Override
    public abstract T getById(int id);

    @Override
    public abstract List<T> getAll();
    
}
